package com.zrgg.futuwen.base;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;

import com.zrgg.futuwen.app.MyApp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import rx.Observable;
import rx.functions.Func0;


public class SystemUtil {









    /**
     * 打开相册
     */
    public static void openFileImage(Activity activity) {
        Intent intent_file = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//调用android的图库
        activity.startActivityForResult(intent_file, Constants.FILEIMAGE_REQUEST_CODE);
    }

    /**
     * 照相功能
     */
    public static void cameraMethod(Activity activity, String saveImageDir, String filename) {
        File file = new File(saveImageDir);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return;
            }
        }
        Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File imageFile = new File(filename);
        Uri u = Uri.fromFile(imageFile);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, u);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1600 * 1200);
        activity.startActivityForResult(imageCaptureIntent, Constants.CAMERA_REQUEST_CODE);

    }

    //按规则参数照片的名字
    public static String produceFile() {
        Random ran = new Random();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = sdf.format(new Date()) + ran.nextInt(1000);
        return fileName + ".jpg";
    }

    public static Observable<String> getUploadPath(final Uri uri) {
        return Observable.defer(new Func0<Observable<String>>() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(getRotationPic(uri).getPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static Uri getRotationPic(Uri uri) throws IOException {
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(ContentUriUtil.getPath(MyApp.getInstance().getBaseContext(), uri));
        } catch (IOException e) {
            e.printStackTrace();
        }
        int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        int rotationInDegrees = exifToDegrees(rotation);
        Matrix matrix = new Matrix();
        if (rotation != 0f) {
            matrix.preRotate(rotationInDegrees);
        }

        Bitmap bitmap = MediaStore.Images.Media.getBitmap(MyApp.getInstance().getContentResolver(), uri);

        float w_r = 1000.0f / (float) bitmap.getWidth();
        float h_r = 1000.0f / (float) bitmap.getHeight();
        float ratio = Math.min(w_r, h_r);
        if (ratio < 1.0f) {

            matrix.postScale(ratio, ratio);

        }
        Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

//        bitmap.recycle();

        //create a file to write bitmap data
        File f = new File(MyApp.getInstance().getCacheDir(), "adjustedBitmap" + UUID.randomUUID());
        f.createNewFile();

//Convert bitmap to byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        adjustedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
        byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(bitmapdata);
        fos.flush();
        fos.close();
        return Uri.fromFile(f);
    }

    private static int exifToDegrees(int exifOrientation) {
        if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
            return 90;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
            return 180;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
            return 270;
        }
        return 0;
    }




}
